package main;

import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

import tools.Message;

public class ReceiveControl extends Thread{

	private Selector selector;
	private boolean flag = true;
	
	public ReceiveControl(Selector selector){
		this.selector = selector;
	}
	
	public void run(){
		try{
			while(flag){
				if(selector.select()==0){
					continue;
				}
				for(SelectionKey key : selector.selectedKeys()){
					selector.selectedKeys().remove(key);
					
					if(key.isAcceptable()){
						ServerSocketChannel ssc = (ServerSocketChannel)key.channel();
						
						SocketChannel sc = ssc.accept();
						sc.configureBlocking(false);
						sc.register(selector, SelectionKey.OP_READ);
						
						key.interestOps(SelectionKey.OP_ACCEPT);
					}
					
					if(key.isReadable()){
						SocketChannel sc = (SocketChannel)key.channel();
						String message = Message.getMessage(sc);
						
						String response = "";
						
						String type = Message.getXMLValue("type", message);
						if(type.equals("login")){
							String name = Message.getXMLValue("name", message);
							String pwd = Message.getXMLValue("pwd", message);
							
							if(name.equals("nidaye")&&pwd.equals("muhaha")){
								response = "<type>loginResp</type><resp>yes</resp>";
							}else{
								response = "<type>loginResp</type><resp>no</resp>";
							}
							Message.sendMessage(response, sc);
						}
						
						key.interestOps(SelectionKey.OP_READ);
					}
				}
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
